package com.bsoft.gol.editor.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import ctd.net.rpc.Client;
import com.bsoft.gol.editor.dao.EditorQuestionnaireTitleDAO;
import com.bsoft.gol.editor.editor.*;
import com.bsoft.gol.editor.editor.response.QueryAnswerListResponse;
import com.bsoft.gol.editor.editor.response.QueryEditorUserInfoListResponse;
import ctd.util.JSONUtils;
import hcn.util.BaseResponse;
import hcn.enums.CollectionInfoIdTypeEnum;
import hcn.enums.CollectionInfoTypeEnum;
import hcn.service.base.bo.PrivateDateBo;
import hcn.service.base.bo.PrivateDateCollectBo;
import hcn.util.ResultCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bsoft.gol.editor.service.EditorAnswerApi;
import com.bsoft.gol.editor.service.EditorQuestionnaireApi;
import com.bsoft.gol.editor.utils.CommonUtils;
import com.bsoft.gol.editor.utils.EditorAnswerExcelUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * @author zhangjie
 * @date 2019/6/24
 */
@RestController
@RequestMapping(value = "/api/auth/editorAnswer")
public class EditorAnswerController extends ApiBaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(EditorAnswerController.class);

    @Autowired
    private EditorAnswerApi editorAnswerApi;

    @Autowired
    private EditorQuestionnaireApi editorQuestionnaireApi;

    @Autowired
    private EditorQuestionnaireTitleDAO editorQuestionnaireTitleDAO;

    /**
     * 答案保存
     *
     * @param req
     * @return
     */
    @RequestMapping("/save")
    public Map<String, Object> add(@RequestBody EditorUserInfo req, HttpServletRequest request) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ParseException {
        BaseResponse<String> response = new BaseResponse<>();
        Map<String, Object> resMap = new HashMap<>();
        ;
//        Long uid  = getUid(request);
        if (CommonUtils.isNull(req.getUserId())) {
//            response.setCode(ResultCode.PARAMETERS_EMPTY);
//            response.setMessage("传入参数不能为空");
            resMap.put("code", ResultCode.PARAMETERS_EMPTY);
            resMap.put("message", "传入参数不能为空");
            return resMap;
        }
        //--------------------------------用户隐私 ---start
        LOGGER.info("---------------数据埋点api/auth/editorAnswer/save结束-------------------------------");
        PrivateDateCollectBo collectBo = new PrivateDateCollectBo();
        //获取用户id
        String userid = req.getUserId();
//        String userid = RpcUserToken.getUserId();
        collectBo.setUserId(userid);
        byte infoType = Byte.valueOf(CollectionInfoTypeEnum.J_USE_INFO.getKey());
        List<PrivateDateBo> infoList = new ArrayList<>();
        PrivateDateBo dateBo = new PrivateDateBo();
        dateBo.setInfoId(Integer.valueOf(CollectionInfoIdTypeEnum.J_CASE_HISTORY_INFO.getKey()));
        dateBo.setInfoType(infoType);
        dateBo.setUsePurpose(CollectionInfoIdTypeEnum.J_CASE_HISTORY_INFO.getPurpose());
        dateBo.setUseScene(CollectionInfoIdTypeEnum.J_CASE_HISTORY_INFO.getScene());
        infoList.add(dateBo);
        PrivateDateBo dateBo1 = new PrivateDateBo();
        dateBo1.setInfoId(Integer.valueOf(CollectionInfoIdTypeEnum.J_EPIDEMIOLOGICAL_INFO.getKey()));
        dateBo1.setInfoType(infoType);
        dateBo1.setUsePurpose(CollectionInfoIdTypeEnum.J_EPIDEMIOLOGICAL_INFO.getPurpose());
        dateBo1.setUseScene(CollectionInfoIdTypeEnum.J_EPIDEMIOLOGICAL_INFO.getScene());
        infoList.add(dateBo1);
        collectBo.setInfoList(infoList);
//        prDaCollectChecklistService.addCollectTimes(collectBo);
        try {
            Client.rpcInvoke("hcn.prDaCollectChecklistService", "addCollectTimes", collectBo);
        } catch (Throwable throwable) {
            LOGGER.error("居民端-个人隐私收集出错-api/auth/editorAnswer/save:" + throwable.getMessage());
        }
        LOGGER.info("---------------数据埋点api/auth/editorAnswer/save结束-------------------------------");
        //-----------------------------------------用户隐私 ---end
        req.setUserId(req.getUserId());
        if (CommonUtils.isNull(req.getCreateId())) {
            req.setCreateId(req.getUserId());
        }
        // 删除此问卷人表单的所有答案，再新增答案
        if (CommonUtils.isNull(req.getQuestionnaireId())
                || CommonUtils.isNull(req.getAnswers())
        ) {
//            response.setCode(ResultCode.PARAMETERS_EMPTY);
//            response.setMessage("传入参数不能为空");
            resMap.put("code", ResultCode.PARAMETERS_EMPTY);
            resMap.put("message", "传入参数不能为空");
            return resMap;
        }
        //限制第一题 选择分数不能为0
        LOGGER.info("参数打印输出1==============================》"+JSONUtils.writeValueAsString(req.getAnswers().get(0).getAnswerContent()));
        LOGGER.info("参数打印输出2==============================》"+JSONUtils.writeValueAsString(req.getAnswers().get(0).getAnswerContent().equals("0")));
        if (CommonUtils.isNotEmpty(req.getAnswers())&&  (req.getAnswers().get(0).getAnswerContent().equals("0"))){
            resMap.put("code", ResultCode.PARAMETERS_EMPTY);
            resMap.put("message", "评分不能为空");
            return resMap;
        }
        //判断问卷内容是否为空
        if (CommonUtils.isNotEmpty(req.getAnswers())) {
            List<EditorQuestionnaireTitle> editorQuestionnaireTitles = new ArrayList<>();
            List<String> titleIds = req.getAnswers().stream().map(answer -> answer.getTitleId()).collect(Collectors.toList());
            List<EditorTitleTemp> editorTitleTemps = req.getAnswers().stream().map((answer) -> {
                EditorTitleTemp editorTitleTemp = new EditorTitleTemp();
                editorTitleTemp.setTitleId(answer.getTitleId());
                editorTitleTemp.setAnswerContent(answer.getAnswerContent());
                editorTitleTemp.setOptionType(answer.getOptionType());
                return editorTitleTemp;
            }).collect(Collectors.toList());
            if (CommonUtils.isNotEmpty(titleIds)) {
                editorQuestionnaireTitles = editorQuestionnaireTitleDAO.queryEditorQuestionnaireTitleByTitleIds(titleIds);
                for (EditorQuestionnaireTitle editorQuestionnaireTitle : editorQuestionnaireTitles) {
                    //查询所有的题目信息,判断是不是必填
                    for (EditorTitleTemp editorTitleTemp : editorTitleTemps) {
                        if (editorTitleTemp.getTitleId().equals(editorQuestionnaireTitle.getTitleId()) && (byte) 1 == editorQuestionnaireTitle.getWriteFlag()) {
                            if (CommonUtils.isEmpty(editorTitleTemp.getAnswerContent())) {
                                resMap.put("code", ResultCode.PARAMETERS_EMPTY);
                                resMap.put("message", "必填题目未填写");
                                return resMap;
                            }
                            //矩阵类型
                            if (editorTitleTemp.getOptionType()==9 || editorTitleTemp.getOptionType() == 21 ||
                                    //检验记录
                                    editorTitleTemp.getOptionType() == 22 ||
                                    //门诊情况
                                    editorTitleTemp.getOptionType()== 23 ||
                                    //住院情况
                                    editorTitleTemp.getOptionType() == 24 ||
                                    //手术操作
                                    editorTitleTemp.getOptionType()== 25 ||
                                    //病历记录
                                    editorTitleTemp.getOptionType()== 34 ||
                                    //病理记录
                                    editorTitleTemp.getOptionType() == 36 ||
                                    //评估评分
                                    editorTitleTemp.getOptionType()== 37 ||
                                    //用药记录
                                    editorTitleTemp.getOptionType() == 38 ||
                                    //门诊处置
                                    editorTitleTemp.getOptionType()== 39){
                                AtomicBoolean notEmpty= new AtomicBoolean(false);
                                JSONArray array = JSONObject.parseArray(editorTitleTemp.getAnswerContent());
                                array.remove(0);
                                for (int i = 0; i <array.size() ; i++) {
                                    JSONArray jsonArray = array.getJSONArray(i);
                                    List<EditorTitleOption> editorTitleOptions = jsonArray.toJavaList(EditorTitleOption.class);
                                    if (CommonUtils.isNotEmpty(editorTitleOptions)){
                                        editorTitleOptions.remove(0);
                                        editorTitleOptions.forEach(e->{
                                            if (StringUtils.isNotEmpty(e.getOptionContent())&& !"[]".equals(e.getOptionContent())){
                                                notEmpty.set(true);
                                            }
                                        });
                                    }

                                }
                                if (!notEmpty.get()){
                                    resMap.put("code", ResultCode.PARAMETERS_EMPTY);
                                    resMap.put("message", "必填题目未填写");
                                    return resMap;
                                }
                            }
                        }
                    }
                }
            }
        }
        resMap = editorAnswerApi.saveBatch(req);
        return resMap;
    }

    /**
     * 答案列表
     *
     * @param req
     * @return
     */
    @RequestMapping("/list")
    public BaseResponse<QueryEditorUserInfoListResponse> list(@RequestBody EditorUserInfo req) {

        BaseResponse<QueryEditorUserInfoListResponse> baseResponse = editorAnswerApi.list(req);


        return baseResponse;
    }

    /**
     * 查询题目版本
     *
     * @param req
     * @return
     */
    @RequestMapping("/questionVersion")
    public BaseResponse<List<Map<String, Object>>> questionVersion(@RequestBody EditorUserInfo req) {
        BaseResponse<List<Map<String, Object>>> response = new BaseResponse<>();
        List<Map<String, Object>> list = editorQuestionnaireApi.questionVersion(req.getQuestionnaireId());
        response.setData(list);
        return response;
    }

    @RequestMapping("/export")
    public void export(@RequestBody EditorUserInfo req, HttpServletResponse response) {
        List<EditorUserInfo> editorAnswerList = editorAnswerApi.listAll(req);
        try {
            byte[] data = EditorAnswerExcelUtil.getExcelAsByteArray(editorAnswerList);
            String fileName;
            fileName = URLEncoder.encode("问卷列表.xlsx", "UTF-8");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(data);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 题目列表
     *
     * @param req
     * @return
     */
    @RequestMapping("/answerList")
    public BaseResponse<QueryAnswerListResponse> list(@RequestBody EditorQuestionnaireTitle req) {

        BaseResponse<QueryAnswerListResponse> baseResponse = editorAnswerApi.queryQuestionnaireAnswerList(req);


        return baseResponse;
    }


}
